import styles from './index.less';
import { useState, useEffect, Props } from 'react';
import { useIntl } from 'umi';
import { Button, Tag, Popover, Input, message, Space } from 'antd';
import { CloseOutlined } from '@ant-design/icons';
import request from '@/utils/request';

const colors = [
  'magenta-inverse',
  'red-inverse',
  'volcano-inverse',
  'orange-inverse',
  'gold-inverse',
  'lime-inverse',
  'green-inverse',
  'cyan-inverse',
  'blue-inverse',
  'geekblue-inverse',
  'purple-inverse',
];

interface DataProps {
  contactId: Number;
  submited: Function;
}

const Labels = function (props: DataProps) {
  const intl = useIntl();

  const [tagList, setTagList] = useState([]);

  useEffect(() => {
    if (props.contactId) {
      getTagsByContact();
    }
  }, [props.contactId]);

  const [tagNames, setTagNames] = useState([
    {
      tagName: String,
      count: Number,
    },
  ]);

  const [addVisible, setAddVisible] = useState(false);
  const [addKeyword, setAddKeyword] = useState('');

  const getTags = () => {
    request
      .get('/tag/tagNames')
      .then((res) => {
        setTagNames(res.data.tagNames || []);
      })
      .catch(() => {
        setTagNames([]);
      });
  };

  const getTagsByContact = () => {
    request
      .get(`/tag/${props.contactId}`)
      .then((res) => {
        setTagList(res.data.tagList || []);
      })
      .catch(() => {
        setTagList([]);
      });
  };

  useEffect(() => {
    getTags();
  }, []);

  useEffect(() => {
    if (addVisible) {
      getTags();
    }
  }, [addVisible]);

  const onClose = (item: any) => {
    request.delete(`/tag/${item.id}`).then((res) => {
      message.success(intl.formatMessage({ id: 'removesuccess' }));
      getTagsByContact();
      props.submited && props.submited();
    });
  };

  const addVisibleChange = (Visible: boolean) => {
    setAddVisible(Visible);
    setAddKeyword('');
  };
  const onAddTag = (item: any) => {
    onSubmitAddTag(item);
  };
  const onSubmitAddTag = (item: any) => {
    const data = {
      tagName: item.tagName,
      contactId: props.contactId,
      color: item.color || colors[Math.floor(Math.random() * 10)],
    };
    addVisibleChange(false);
    request.post(`/tag/create`, data).then((res) => {
      message.success(intl.formatMessage({ id: 'addsuccess' }));
      props.submited && props.submited();
      getTags();
      getTagsByContact();
    });
  };

  const onChangeAddInput = (e: any) => {
    const { value } = e.target;
    setAddKeyword(value);
  };

  const showThisTag = (m: any) => {
    const hasTagList = tagList.find((n) => n.tagName === m.tagName);
    const hasKeyword = addKeyword
      ? m.tagName.indexOf(addKeyword) < 0
      : addKeyword;
    return !hasTagList && !hasKeyword;
  };

  const addBlock = () => {
    return (
      <div className={styles.dropdownBox}>
        <Input
          placeholder={intl.formatMessage({ id: 'search_create_label' })}
          value={addKeyword}
          onChange={onChangeAddInput}
        ></Input>
        <div className={styles.lists}>
          {tagNames.map((n, i) =>
            showThisTag(n) ? (
              <div key={i} className={styles.list}>
                <Tag
                  color={n.color}
                  className={styles.tag}
                  onClick={() => onAddTag(n)}
                >
                  {n.tagName}
                </Tag>
                {n.count}
              </div>
            ) : null,
          )}
          {addKeyword &&
          !tagNames.filter((n) => n.tagName === addKeyword).length ? (
            <div
              className={styles.create}
              onClick={() => onSubmitAddTag({tagName: addKeyword})}
            >
              {intl.formatMessage({ id: 'createlabel' })}'{addKeyword}'
            </div>
          ) : null}
        </div>
      </div>
    );
  };

  return (
    <div className={styles.labels}>
      <div className={styles.head}>
        <div className={styles.title}>
          {intl.formatMessage({ id: 'label' })}
        </div>
      </div>
      <div className={styles.tags}>
        {tagList.map((n, i) => (
          <Tag key={i} color={n.color} className={styles.tag}>
            {n.tagName}
            <CloseOutlined onClick={() => onClose(n)} />
          </Tag>
        ))}
      </div>

      <Popover
        visible={addVisible}
        placement="topRight"
        content={addBlock}
        trigger={['click']}
        onVisibleChange={addVisibleChange}
      >
        <Button onClick={() => addVisibleChange(true)}>
          {intl.formatMessage({ id: 'addLabel' })}
        </Button>
      </Popover>
    </div>
  );
};

export default Labels;
